package com.example.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring容器工具类
 *
 * @author 别人
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {

    private static String env;
    private static String contextPath;
    private static ApplicationContext applicationContext;

    // @Value("${spring.cloud.nacos.config.namespace}")
    public void setEnv(String env) {
        SpringContextUtils.env = env;
    }

    // @Value("${server.servlet.context-path}")
    public void setContextPath(String contextPath) {
        SpringContextUtils.contextPath = contextPath;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return SpringContextUtils.applicationContext.getBean(name, clazz);
    }

    public static <T> T getBean(Class<T> clazz) {
        return SpringContextUtils.applicationContext.getBean(clazz);
    }

    public static String getApplicationName() {
        return SpringContextUtils.applicationContext.getApplicationName().substring(1);
    }

    public static String getEnv() {
        return SpringContextUtils.env;
    }

    public static String getContextPath() {
        return contextPath;
    }
}
